<template>
  <div>
    <div>
      <InputTextArea
        v-model:value="conds"
        :rows="5"
        :readonly="isScriptEditable > 0"
        @change="handleChangeConds"
      />
    </div>
    <div class="flex flex-wrap gap-2 items-center">
      <div>
        字段
        <Select
          style="width: 130px"
          placeholder="请选择"
          :options="formGetFieldsData"
          :field-names="{ label: 'title', value: 'name' }"
          @change="handleChangeField"
          optionFilterProp="title"
          showSearch
        />
      </div>

      <Dropdown class="ml-2">
        <span
          >预置参数
          <DownOutlined />
        </span>
        <template #overlay>
          <Menu @click="({ key }) => handleClickItem(key)">
            <MenuItem :key="item.value" v-for="item in tjList" :title="item.descrip">
              {{ item.label }}
            </MenuItem>
          </Menu>
        </template>
      </Dropdown>

      <Dropdown class="ml-2">
        <span
          >预置脚本
          <DownOutlined />
        </span>
        <template #overlay>
          <Menu @click="({ key }) => handleClickMenu(key, record)">
            <MenuItem :key="k.value" v-for="k in dropdownMenuOptions">
              {{ k.label }}
            </MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <a-button
        type="primary"
        @click="handleDesign"
        class="mt-2 mb-2"
        :disabled="isScriptEditable == 2"
        >设计器</a-button
      >
    </div>
    <div> (注：条件不能以and开头，可以直接输入条件，也可以使用脚本，脚本中必须返回ret) </div>
    <DesignIframe ref="ifrmRef" @register="registerDesignIframeView" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref, unref, onUnmounted, watch, onMounted } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { Input, Select, message, Dropdown, Menu } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { DesignIframe } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/index';
  import { useUserStore } from '/@/store/modules/user';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { DownOutlined } from '@ant-design/icons-vue';

  const InputTextArea = Input.TextArea;
  const { currentRoute } = useRouter();
  const MenuItem = Menu.Item;
  const isScriptEditable = ref(0);

  const emit = defineEmits(['update:modelValue', 'updateFilterField']);
  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
    formGetFieldsData: {
      type: Array as PropType<any>,
      default: () => [],
    },
  });

  const setEimt = () => {
    emit('update:modelValue', conds.value);
  };
  const conds = ref('');

  watch(
    () => props.modelValue,
    (newVal) => {
      conds.value = newVal;
    },
    {
      immediate: true,
    },
  );
  const [registerDesignIframeView, { openModal, closeModal }] = useModal();
  const handleDesign = () => {
    openModal(true, {
      scriptStr: unref(conds),
      formCode: currentRoute.value?.query?.formCode,
    });
  };
  const handleSuccess = (value) => {
    console.log('handleSuccess', value);
    if (value) {
      conds.value = value;
      setEimt();
    }
  };

  const tjList = [
    {
      label: 'request参数',
      value: '{$request.key}',
      descrip: '从request请求中获取参数',
    },
    {
      label: '当前日期',
      value: '{$curDate}',
      descrip: '当前日期',
    },
    {
      label: '当前用户',
      value: '={$curUser}',
      descrip: '当前用户',
    },
    {
      label: '当前用户所在的部门',
      value: 'in ({$curUserDept})',
      descrip: '当前用户所在的部门',
    },
    {
      label: '当前用户的角色',
      value: 'in ({$curUserRole})',
      descrip: '当前用户的角色',
    },
    {
      label: '当前用户管理的部门',
      value: 'in ({$admin.dept})',
      descrip: '用户可以管理的部门',
    },
    {
      label: '主表ID',
      value: '{$mainId}',
      descrip: '主表ID',
    },
  ];

  const handleClickItem = (value) => {
    conds.value += ` ${value}`;
    setEimt();
  };

  const formGetFieldsDataMian = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataMian = () => {
    try {
      if (currentRoute.value?.query.formCode) {
        getFormGetFields({ formCode: currentRoute.value.query.formCode }).then((res) => {
          formGetFieldsDataMian.value = res || [];
          if (isArray(formGetFieldsDataMian.value)) {
            formGetFieldsDataMian.value.forEach((item) => {
              delete item.options;
            });
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  const handleChangeConds = () => {
    setEimt();
  };

  //选择字段操作
  const handleChangeField = (val) => {
    conds.value += val;
    setEimt();
  };

  const dropdownMenuOptions = [
    {
      value: 1,
      label: '流程中的处理人员可浏览',
    },
  ];
  const handleClickMenu = (key, record) => {
    if (key == 1) {
      conds.value =
        'select distinct t1.id from ft_' +
        currentRoute.value?.query?.formCode +
        ' t1, flow_my_action t100 where t1.flowid=t100.flow_id and t100.user_name={$curUser} and cws_status=1';
      setEimt();
    }
  };

  const fetch = async () => {
    await getFormGetFieldsDataMian();
    let serverInfo = userStore.getServerInfo;
    isScriptEditable.value = serverInfo.isScriptEditable;
    console.log('isScriptEditable', isScriptEditable.value);
  };

  onMounted(fetch);

  const userStore = useUserStore();
  const ifrmRef = ref<any>(null);
  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      conds.value = data;
      setEimt();
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', conds.value);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'module.filter',
        data: conds.value ? conds.value : '',
      };
      // window.postMessage(data, '*');
      unref(ifrmRef)?.doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }
  onUnmounted(() => {
    console.log('NodeEdit-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });
</script>
